import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Tag, Modal, message} from 'antd';
import { observer } from 'mobx-react-lite';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, TeamOutlined } from '@ant-design/icons';
import * as Icons from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import PermissionForm from './components/PermissionForm';
import { Permission} from './store/permissionTypes';
import { permissionStore } from './store/permissionStore';

const PermissionList: React.FC = observer(() => {
  useEffect(() => {
    permissionStore.fetchPermissions();
    permissionStore.getActiveRole();
    permissionStore.getActiveMenuTree();
  }, []);
  
  const navigate = useNavigate();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingPermission, setEditingPermission] = useState<Permission | null>(null);
  const [modalType, setModalType] = useState<'create' | 'edit' | 'view'> ('create');

  const getRoleNameTag = (roleId: string) => {
    const roleMap = permissionStore.roleValues;
    const config = roleMap && roleMap[roleId as keyof typeof roleMap];
      return config ? <Tag color={config.color}>{config.title}</Tag> : null;
  };

  const columns = [
    {
      title: '权限名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '权限编码',
      dataIndex: 'perCode',
      key: 'perCode',
    },
    {
      title: '关联菜单',
      dataIndex: 'menuId',
      key: 'menuId',
      render: (_: any, record: Permission) => (
        <Tag color={record.perType === 'resource' ? 'error' : 'error'}>
          {record.name}
        </Tag>
      ),
    },
    {
      title: '权限类型',
      dataIndex: 'perType',
      key: 'perType',
      render: (perType: string) => (
        <Tag color={perType === 'resource' ? 'success' : 'error'}>
          {perType === 'resource' ? '菜单' : '操作'}
        </Tag>
      ),
    },
    {
      title: '已分配角色',
      dataIndex: 'roles',
      key: 'roles',
      render: (roles: string[]) => (
        <Space>
          {roles && roles.map(role => (
           <>{getRoleNameTag(role)}</>
          ))}
        </Space>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Permission) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          <Button
            type="link"
            disabled
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            disabled
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleCreate = () => {
    setModalType('create');
    setEditingPermission(null);
    setIsModalVisible(true);
  };

  const handleEdit = (record: Permission) => {
   
    setModalType('edit');
    setEditingPermission(record);
    setIsModalVisible(true);
  };

  const handleView = (record: Permission) => {
    setModalType('view');
    setEditingPermission(record);
    setIsModalVisible(true);
  };


  const handleDelete = (record: Permission) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除权限 ${record.name} 吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        permissionStore.deletePermission(record.id);
        message.success('删除成功');
      },
    });
  };

  const handleModalClose = () => {
    setIsModalVisible(false);
    setEditingPermission(null);
  };

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleCreate}
        >
          新建权限
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={Array.isArray(permissionStore.permissions) ? permissionStore.permissions : []}
        rowKey="id"
        loading={permissionStore.loading}
        locale={{ emptyText: '暂无数据' }}
      />

      <Modal
        title={
          modalType === 'create'
            ? '新建权限'
            : modalType === 'edit'
            ? '编辑权限'
            : '查看权限'
        }
        open={isModalVisible}
        onCancel={handleModalClose}
        footer={null}
        width={800}
        destroyOnClose
      >
        <PermissionForm
          type={modalType}
          initialValues={editingPermission}
          onCancel={handleModalClose}
        />
      </Modal>
    </div>
  );
});

export default PermissionList; 